package adminService

import (
	"fmt"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"

	"gorm.io/gorm"
)

// 根据管理员权限获取查询条件
func GetUserRulesWhere(adminId int) (where map[string]interface{}, err error) {
	where = make(map[string]interface{})

	db := model.GetInstance().GetDB()

	var adminWithGroup []int
	if err = db.Model(&adminModel.AdminWithGroupStruct{}).
		Where("admin_id = ?", adminId).
		Select("admin_group_id").
		Scan(&adminWithGroup).Error; err != nil {
		err = fmt.Errorf("获取管理员权限组失败%s", err.Error())
		return
	}

	// 管理员没有分组
	if len(adminWithGroup) == 0 {
		where["admin_id"] = adminId
		return
	}

	var adminGroup []adminModel.AdminGroupStruct
	if err = db.Model(&adminModel.AdminGroupStruct{}).
		Where("id in ?", adminWithGroup).
		Find(&adminGroup).Error; err != nil {
		where["admin_id"] = adminId
		return
	}

	// 管理员组菜单为*
	for _, v := range adminGroup {
		if v.Rules == "*" {
			return
		}
	}

	where["admin_id"] = adminId

	return
}

// 获取管理员名称
func GetAdminName(adminId int) (name string, err error) {
	var admin adminModel.AdminStruct
	db := model.GetInstance().GetDB()

	if err = db.Where("id = ?", adminId).First(&admin).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return "", nil
		}

		err = fmt.Errorf("获取管理员名称失败%s", err.Error())
		return
	}

	name = admin.Username
	return
}
